var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');
var app = getApp();
var isPosting = false;
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
});
var oldData = '';
var isEdit = false;
var releaseUid = '';

var selCol_1 = 0;
var isAdmin=false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    isAdmin: isAdmin,
    minHeight: 0,
    show_addClass_view: false,
    
    uploadImg: [],
    token: "",
    uid: 0,
    imgWH: 0,
    allArtArray:[],
    classlysAllData:[],
    classlysData: [],
    selValue:[],
    selClassly: {},
    titleValue: '',
    sellpriceValue:'',
    yunfeiValue:'',
    kucunValue: '',
    switchChecked: false,
    peopleValue: {'uid': '0', 'uname': ''},
    message: '',
    date: '',
    startDate: '',
    endDate: '',
    videosArray: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    selCol_1 = 0;
    releaseUid = options.releaseuid ? options.releaseuid : '';
    oldData = '';
    isEdit = false;
    if (options.data) {//有数据传过来，说明是编
      wx.showLoading({
        title: '加载中',
      })
      oldData = JSON.parse(base64.decode(options.data));
      isEdit = true;
      releaseUid = oldData.user.uid;
      console.log("要编辑的数据：", oldData);
    } else if (options.artid && options.artname) {
      this.setData({
        peopleValue:{
          'uid': options.artid ? options.artid : '',
          'uname': options.artname ? options.artname : '',
        }
      })
    }
    var curDate = new Date();
    var curYear = curDate.getFullYear();
    var curDate_f = util.formatTime(curDate, '-', '');
    var startDate_f = util.formatTime(new Date(curYear - 50, 0, 1), '-', '');
    var endDate_f = util.formatTime(new Date(curYear + 49, 11, 31), '-', '');
    console.log("curDate_f = " + curDate_f + "; startDate_f = " + startDate_f + "; endDate_f = " + endDate_f);
    this.setData({
      date: curDate_f,
      startDate: startDate_f,
      endDate: endDate_f
    });
    this.load();
    var that = this;
    //获取所有合作艺术家
    that.loadAllArtist();
    //获取商品 分类
    that.loadClasslyData();
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          token: res.token
        });
        if (!releaseUid){
          releaseUid = res.uid;
        }
      }
    });
    if (util.orgid == 17784) {
      wx.setNavigationBarTitle({
        title:  '课程',
      })

    }
  },
  load: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          minHeight: res.windowHeight - 40,
          imgWH: (res.windowWidth - 18) / 4 - 12
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      // that.resetNavColor();
    });
    if(isEdit){
      var photoArray = [];
      if (oldData.photos) {
        photoArray = oldData.photos.split(',');
      }
      var videoArray = [];
      if (oldData.video) {
        videoArray = oldData.video.split(',');
      }
      var selClassly = { name: oldData.gtypename, id: oldData.gtype};
      var people = { 'uid': '0', 'uname': '' };
      if (oldData.people && oldData.people.username){
        people = { 'uid': oldData.people.uid, 'uname': oldData.people.username };
      }
      var isHuiyuan = (oldData.huyuan == 1);
      this.setData({
        selClassly: selClassly,
        titleValue: oldData.topictitle,
        sellpriceValue: oldData.sellprice/100,
        yunfeiValue: oldData.yunfei/100,
        kucunValue: oldData.kucun,
        switchChecked: isHuiyuan,
        peopleValue: people,
        message:oldData.message,
        uploadImg:photoArray,
        videosArray: videoArray,
      })
      wx.hideLoading();
    }
  },


  loadAllArtist: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getbinduser"
      },
      success: function (responseData) {
        console.log("合作艺术家：", responseData.data);
        that.setData({
          allArtArray:responseData.data
        });
      }
    });
  },

  bindPickerSelArtist:function(e) {
    var index = e.detail.value;
    var that = this;
    this.setData({
      peopleValue: that.data.allArtArray[index],
    })
    releaseUid = that.data.peopleValue.uid == '0' ? that.data.uid : that.data.peopleValue.uid;
  },

  loadClasslyData: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": isAdmin ? "goodstype" :"goodstypeghs",
        'uid': releaseUid
      },
      success: function (responseData) {
        console.log("goodstype", responseData.data);
        var gtypeArray = that.buildPickerData(responseData.data, 0);

        gtypeArray[1].push({ title: "增加分类" })
        that.setData({
          classlysAllData: responseData.data,
          classlysData: gtypeArray,
        });

      }
    });
  },

  buildPickerData: function(allData, index1){
    var gtypeArray = [];
    gtypeArray[0] = allData;
    var child1 = allData[index1].child;
    
    if (child1 && child1.length > 0){
      gtypeArray[1] = child1;
    } else {
      gtypeArray[1] = [];
    }
    console.log("商品分类数组：", gtypeArray);
    return gtypeArray;
  },

  //商品类型选择
  bindPickerSelType: function (e) {
    console.log(e)
    var that=this;
    var index = e.detail.value;
    
    var name = '';
    var id = '';
    for(var i = 0; i < index.length; i++){
      var colOb = this.data.classlysData[i];
      var selIndex = index[i];
      console.log("i = " + i + "; selIndex = " + selIndex);
      if(colOb && colOb.length > 0){
        name = (name + " " + colOb[selIndex].title);
        id = colOb[selIndex].goods_id;
        if (colOb[selIndex].title=='增加分类'){
          console.log("增加分类");
          that.setData({
            show_addClass_view:true
          })
        }
      }
    };
    var selClassly = '';
    if(name && id){
      selClassly = {"id":id, "name": name};
    }
    console.log("改变之后的值：", selClassly);
    
    this.setData({
      selValue: index,
      selClassly: selClassly
    })
  },
  bindColumnChange: function(e){
    var selResult = e.detail;
    // { column: column, value: value }
    console.log("某列改变了：", selResult);
    if(selResult.column == 0){
      selCol_1 = selResult.value;
    }
    var gtypeArray = this.buildPickerData(this.data.classlysAllData, selCol_1);
    this.setData({
      classlysData: gtypeArray,
    });
  },

  //是否会员专属选择
  switchChange: function(e){
    this.setData({
      switchChecked: e.detail.value
    });
  },

  releaseSubmit: function (e) {
    app.saveFormId(e.detail.formId);
    console.log("发布者uid = " + releaseUid);
    if (isPosting) {
      return false;
    }
    isPosting = true;

    var classlyData = this.data.selClassly;//分类
    if (!classlyData || !classlyData.id) {
      app.dialog('请选择商品分类', 'loading');
      isPosting = false;
      return false;
    }

    var title = e.detail.value.title;//名称
    if (!title || title.trim().length <= 0) {
      app.dialog('请输入商品名称', 'loading');
      isPosting = false;
      return false;
    }
    
    var message = e.detail.value.message;//链接
    if (!message || message.trim().length <= 0) {
      app.dialog('请输入商品介绍', 'loading');
      isPosting = false;
      return false;
    }
    var guige=''
    if(util.orgid==17784){

      var userTarget = e.detail.value.userTarget;//链接
      if (!userTarget || userTarget.trim().length <= 0) {
        app.dialog('请输入适合对象', 'loading');
        isPosting = false;
        return false;
      }

      var daysNumber = e.detail.value.daysNumber;//链接
      if (!daysNumber || daysNumber.trim().length <= 0) {
        app.dialog('请输入行程天数', 'loading');
        isPosting = false;
        return false;
      }

      var placeActivity = e.detail.value.placeActivity;//链接
      if (!placeActivity || placeActivity.trim().length <= 0) {
        app.dialog('请输入活动地点', 'loading');
        isPosting = false;
        return false;
      }

      var sellPrice = e.detail.value.sellPrice;//链接
      if (!sellPrice || sellPrice.trim().length <= 0) {
        app.dialog('请输入课程价格', 'loading');
        isPosting = false;
        return false;
      }
      guige = '适合对象：' + userTarget + '|行程天数：' + daysNumber + '|活动地点：' + placeActivity + '|课程价格：' + sellPrice + '元/人';
      console.log('guige',guige)
    }

    var price = e.detail.value.sellPrice ? e.detail.value.sellPrice : 0;
    var yunfei = e.detail.value.yunfei ? e.detail.value.yunfei : 0;
    var kucun = e.detail.value.kucun ? e.detail.value.kucun : 0;
    var people = this.data.peopleValue.uid;
    
    //图片
    var photos = this.data.uploadImg;//选择的图片 	图片的本地文件路径列表
    var photos_param = "";
    if (photos && photos.length > 0) {
      if (photos.length == 0) {
        app.dialog('请上传图片', 'loading');
        isPosting = false;
        return false;
      }
      //data 里面是参数  我不知道是不是用这个接口  你看着改吧  再把内容和图片放里就好了
      var nowd = new Date();
      var nowm = nowd.getMonth() + 1;
      nowm = nowm.toString();
      if (parseInt(nowm) < 10) {
        nowm = '0' + nowm;
      }
      var nowda = nowd.getDate();
      nowda = nowda.toString();
      if (parseInt(nowda) < 10) {
        nowda = '0' + nowda;
      }
      var nowhour = nowd.getHours();
      nowhour = nowhour.toString();
      if (parseInt(nowhour) < 10) {
        nowhour = '0' + nowhour;
      }
      photos_param = photos.map(function (item) { return item.replace('wxfile://tmp_', util.upyun_imgHost + '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(',');
    } else {
      app.dialog('请添加商品图片', 'loading');
      isPosting = false;
      return false;
    }

    // wx.showLoading({ title: '发布中，请稍等' });
    wx.showLoading({ title: '发布中...' });

    var video = '';
    if (this.data.videosArray.length > 0) {
      video = this.data.videosArray.map(function (item) { return item }).join(',')
    }

    var action = "posttopic";
    if (isEdit) {
      action = "edittopic";
    }
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + action + token);//私钥
    
    var data = {
      ac: action,
      privatekey: privatekey,
      topictype: 4,
      gtype: classlyData.id,//系统类别
      gtypename: classlyData.name,
      uid: uid,
      postuid: releaseUid,
      topictitle: title,
      guige: guige,
      sellprice:price*100,
      yunfei: yunfei*100,
      kucun: kucun,
      people: people,
      message: message,
      xcx: 1,
      photos: photos_param,
      video: video
    }
    if (isEdit) {
      data.topicid = oldData.id;
    }
    console.log("商品：", data);
    var that = this;
    util.api({
      data: data,
      method: "POST",
      success: function (responseData) {
        console.log(responseData);
        wx.hideLoading();
        if (responseData.data.id) {//你看是不是这个字段判断发布失败还是成功的
          isPosting = false;
          that.releaseSuccess();
        } else {
          app.dialog('发布失败', 'loading');
          isPosting = false;
        }

      },
      fail: function (e) {
        isPosting = false;
        wx.hideLoading();
      }
    });
  },

  releaseSuccess: function () {
    var pages = getCurrentPages();
    var curPageIndex = pages.length;
    var delta = curPageIndex - 2;
    if (delta <= 1) {
      wx.reLaunch({ url: "/pages/shopping-mall/shopping-mall" });
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },

  uploadImgs: function () {
    var that = this;
    var photos = this.data.uploadImg;
    if (photos.length >= 9) {
      app.dialog('最多上传9张图片', 'loading');
      return false;
    }
    
    wx.chooseImage({
      count: (9 - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({ title: '图片上传中..', mask: 'true' });
        const tempFilePaths = res.tempFilePaths;
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        for (var photoi = 0; photoi < tempFileCount; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              // jobj.put("url", recordUrl);
              // jobj.put("name", imgFileName);
              // jobj.put("type", resJob.optString("mimetype"));
              // jobj.put("size", resJob.optInt("file_size"));
              // jobj.put("hash", resJob.optString("sign"));
              // jobj.put("extension", resJob.optString("image-type"));
              // jobj.put("save_path", savePath);
              // jobj.put("save_name", savename);
              // jobj.put("width", resJob.optInt("image-width"));
              // jobj.put("height", resJob.optInt("image-height"));
            },
            fail: function ({ errMsg }) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
        //wx.hideLoading();
      },
      fail: function ({ errMsg }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  //删除图片
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index, 1);
    this.setData({
      uploadImg: photos
    });
  },

  addClassEdit: function (e) {
    var name = e.currentTarget.dataset.name;
    this.setData({
      className: e.detail.value
    })
  },

  hiddenEditView: function () {
    this.setData({
      show_addClass_view: false,
    });
  },

  addClassAction: function () {
    var className = this.data.className;
    if (className == '中文|English') {
      app.dialog("请输入分类名字", 'loading');
      return;
    }
    if (className.indexOf('|') <= 0 || className.indexOf('|') == className.length - 1) {
      app.dialog("请使用 '|' 分隔中、英文名", 'loading');
      return;
    }
    this.addClassly();
  },

  addClassly: function () {
    var that = this;

    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + 'addalbum' + token);//私钥

    var params = {
      ac: "addalbum",
      privatekey: privatekey,
      name: that.data.className,
      uid: uid,
      type: 3
    }
    console.log("addalbum params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("add作品类别：", result);
        if (result.msg) {

        } else {
          that.setData({
            classlysData: result,
            show_addClass_view: false,
            selClassly: result[0]
          });
        }

      }
    });
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },

  //添加视频链接
  addVideoLink: function () {
    var newVideoArray = this.data.videosArray.concat('');
    this.setData({
      videosArray: newVideoArray
    });
  },
  //编辑视频链接  失去焦点时调用
  editVideoLinkFinish: function (e) {
    var videoIndex = e.currentTarget.dataset.index;
    var vidArray = this.data.videosArray;
    vidArray[videoIndex] = e.detail.value;

    this.setData({
      videosArray: vidArray
    });
  },
  //删除视频链接
  delVideoLink: function (e) {
    var videoIndex = e.currentTarget.dataset.index;
    var vidArray = this.data.videosArray;
    vidArray.splice(videoIndex, 1);
    this.setData({
      videosArray: vidArray
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  addGoodsType:function(){
    var that = this;

    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + 'addgoodstype' + token);//私钥

    var params = {
      ac: "addgoodstype",
      privatekey: privatekey,
      title: that.data.className,
      uid: uid,
    }
    console.log("addgoodstype: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("add类别：", result);
        if (result.msg) {

        } else {
          var gtypeArray = that.buildPickerData(responseData.data, 0);

          gtypeArray[1].push({ title: "增加分类" })
          that.setData({
            classlysAllData: responseData.data,
            classlysData: gtypeArray,
            show_addClass_view: false,
          });
          // that.setData({
          //   classlysData: result,
          //   show_addClass_view: false,
          //   selClassly: result[0]
          // });
        }

      }
    });
  }

})